package com.cuitrip.business.user;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.cuitrip.apiservice.CommonBusiness;
import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.component.item.ItemLayout;
import com.cuitrip.service.R;
import com.cuitrip.util.ImageFetcherManager;
import com.cuitrip.util.MediaFetcher;
import com.cuitrip.util.PlatformUtil;
import com.cuitrip.util.track.TrackUtil;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.logtrack.AppLog;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.proxy.ApiProxy;
import com.lab.network.proxy.ApiProxyBuilder;
import com.lab.network.proxy.ApiProxyCallBack;
import com.lab.photopicker.DefaultCallback;
import com.lab.photopicker.EasyImage;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.GetImageHelper;
import com.lab.utils.ImageHelper;
import com.lab.utils.MessageUtils;
import com.lab.utils.Utils;
import com.lab.utils.imageupload.imp.OssService;
import com.lab.utils.imageupload.model.OssTokenObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.UserInfo;

public class EditSelfInfoActivity extends CustomUiFragmentActivity implements View.OnClickListener {

    /**
     * REQUEST_CODE的格式：3*8位数据
     * c+{请求样式}+{请求内容}
     * {请求样式}:
     * 0->MSelect-2
     * 1->MInput-1
     * 2->MInput-2
     * 3->多选列表
     */
    public static final int REQUEST_CODE_EDIT_NICK_NAME            = 0xc11;
    public static final int REQUEST_CODE_SELECT_COUNTRY_AND_CITY   = 0xc02;
    public static final int REQUEST_CODE_EDIT_JOB                  = 0xc13;
    public static final int REQUEST_CODE_EDIT_HOBBY                = 0xc14;
    public static final int REQUEST_CODE_EDIT_LANGUAGE             = 0xc35;
    public static final int REQUEST_CODE_EDIT_INTRODUCTION         = 0xc26;

    public static final String KEY_PLACE_HOLDER      = "KEY_PLACE_HOLDER";
    public static final String KEY_TIP               = "KEY_TIP";
    public static final String KEY_REQUEST_CODE      = "REQUEST_CODE";
    public static final String KEY_VALUE             = "KEY_VALUE";
    public static final String KEY_DIALOG_TITLE      = "KEY_DIALOG_TITLE";
    public static final String KEY_DIALOG_CONTENT    = "KEY_DIALOG_CONTENT";
    public static final String KEY_VALUE_MAX_LENGTH  = "KEY_VALUE_MAX_LENGTH";
    public static final String KEY_SELECTED_VALUES   = "KEY_SELECTED_VALUES";
    public static final String KEY_SELECT_ARRAY      = "KEY_SELECT_ARRAY";

    @Bind(R.id.author_img)
    CircleImageView authorImg;
    @Bind(R.id.viewNickName)
    ItemLayout viewNickName;
    @Bind(R.id.viewHobby)
    ItemLayout viewHobby;
    @Bind(R.id.viewIntroduction)
    ItemLayout viewIntroduction;
    @Bind(R.id.viewCity)
    ItemLayout viewCity;
    @Bind(R.id.viewJob)
    ItemLayout viewJob;
    @Bind(R.id.viewLanguage)
    ItemLayout viewLanguage;
    private File tempPhotoFile;
    private ImageFetcherManager mImageFetcherManager;
    private String mUploadedAvaUrl;
    private ApiProxy apiProxy;
    private OssService ossService = new OssService();

    private IProxyCallback modiftUserInfoCallback  = new ApiProxyCallBack<CtUserInfo>() {
        @Override
        public void doPreWork(CtApiResponse response) {
            hideLoading();
        }

        @Override
        public boolean onSuccess(CtUserInfo userInfo, CtApiResponse response) {
            if (userInfo != null) {
                RongIM.getInstance().refreshUserInfoCache(new UserInfo(userInfo.getUid(), userInfo.getNick(), Uri.parse(userInfo.getHeadPic())));
                CtUserInfo info = LoginInstance.updateProfile(AppCoreRuntime.context, userInfo, false);
                if (info == null) {
                    return super.onSuccess(userInfo, response);
                }
                if (LoginInstance.getInstance().getUserInfo() != null) {
                    LoginInstance.getInstance().getUserInfo().setHasUnReadMsg(userInfo.getHasUnReadMsg());
                }
            }
            return super.onSuccess(userInfo, response);
        }

        @Override
        public boolean onFaild(CtApiResponse response) {
            String msg;
            if (response != null && !TextUtils.isEmpty(response.msg)) {
                msg = response.msg;
            } else {
                msg = PlatformUtil.getInstance().getString(R.string.feedback_data_err);
            }
            MessageUtils.showToast(msg);
            return super.onFaild(response);
        }
    };

    private IProxyCallback getOssTokenCallback = new ApiProxyCallBack<OssTokenObject>() {
        @Override
        public void doPreWork(CtApiResponse response) {
            hideLoading();
        }

        @Override
        public boolean onSuccess(OssTokenObject ossTokenObject, CtApiResponse response) {
            if (ossTokenObject != null) {
                ossService.initClient(ossTokenObject);
                CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
                ossService.asyncPutImage(OssService.getObjectName(userInfo.getUid(), tempPhotoFile), tempPhotoFile.getAbsolutePath(), new OssService.UploadCallback() {
                    @Override
                    public void onFailure(String errorMessage) {
                    }

                    @Override
                    public void onSuccess(String url) {
                        mUploadedAvaUrl = url;
                        completeAction();
                    }

                    @Override
                    public void onProgress(int progress) {
                        AppLog.d("progress" + progress);
                    }
                });

            }
            return super.onSuccess(ossTokenObject, response);
        }

        @Override
        public boolean onFaild(CtApiResponse response) {
            String msg;
            if (!TextUtils.isEmpty(response.msg)) {
                msg = response.msg;
            } else {
                msg = PlatformUtil.getInstance().getString(R.string.feedback_data_err);
            }
            MessageUtils.showToast(msg);
            return super.onFaild(response);
        }
    };

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config=new CustomUiConfig();
        config.mTopbarMiddleAreaName=getString(R.string.user_group_about);
        config.mTopbarLeftAreaName=getString(R.string.back_icon);
        config.mTopbarRightAreaName=getString(R.string.operation_preview);
        config.mTopbarStyle= CustomUiConfig.BarStyle.WHITE_STYLE;
        return config;
    }

    @Override
    public void onTopbarLeftPress() {
        finish();
    }

    @Override
    public void onTopbarRightPress() {
        TrackUtil.trackScreenName("/user/about");
        PersonActivity.jumpPersonActivity(this, null, LoginInstance.getInstance().getUserInfo().getUid());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState,R.layout.ct_activity_edit_self_info);
        apiProxy = ApiProxyBuilder.getBuilder()
                .addApiCallBack(ApiManager.MODIFY_USERINFO,modiftUserInfoCallback)
                .addApiCallBack(ApiManager.GET_MOBILE_OSS_TOKEN, getOssTokenCallback)
                .build();
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        mImageFetcherManager = new ImageFetcherManager(this, ImageFetcherManager.Source.SELF_INFO_SELECT);
        loadUserProfile();
        viewNickName.setOnClickListener(this);
        viewHobby.setOnClickListener(this);
        viewIntroduction.setOnClickListener(this);
        viewCity.setOnClickListener(this);
        viewJob.setOnClickListener(this);
        viewLanguage.setOnClickListener(this);
    }

    private void loadUserProfile() {
        CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
        if (userInfo==null){
            return;
        }
        viewNickName.setmRightText(userInfo.getNick());
        String city=userInfo.getCity();
        viewCity.setmRightText(city);
        Utils.setRightTextViewValue(viewJob, userInfo.getCareer(), getString(R.string.value_no_set));
        Utils.setRightTextViewValue(viewHobby, userInfo.getInterests(), getString(R.string.value_no_set));
        Utils.setRightTextViewValue(viewLanguage,userInfo.getLanguage(),getString(R.string.value_no_set));
        ImageHelper.displayImage(userInfo.getHeadPic(),authorImg,null);
    }

    @OnClick(R.id.iconLayout)
    public void selectPhoto() {
        tempPhotoFile =
                MediaFetcher.getTempImageFilePath(AppCoreRuntime.context);
        if (tempPhotoFile == null){
            return;
        }
        EasyImage.openChooser(EditSelfInfoActivity.this, "", true);
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        int requestCode=-1;
        switch (v.getId()) {
            case R.id.viewNickName:
                TrackUtil.trackScreenName("/user/about/edit/set/name");
                EditInfoDetailActivity.startActivityWithShowDialig(
                        this, viewNickName.getmRightText().toString(), 60,
                        "", getString(R.string.user_attribute_nickname)
                        , getString(R.string.user_attribute_nickname_save_confirm), getString(R.string.user_attribute_nickname_limit,60),
                        REQUEST_CODE_EDIT_NICK_NAME
                );
                return;
            case R.id.viewCity:
                TrackUtil.trackScreenName("/user/about/edit/set/city");
//                ChooseCityActivity.chooseLocation(this);
                ChooseCityActivity.chooseLocation(this, ChooseCityActivity.PROFILE_MODE,false);
                return;
            case R.id.viewJob:
                TrackUtil.trackScreenName("/user/about/edit/set/work");
                boolean value=viewJob.getmRightText().toString().equals(getString(R.string.value_no_set));
                EditInfoDetailActivity.startActivityWithoutShowDialig(
                        this, getString(R.string.user_attribute_work),value?"":viewJob.getmRightText().toString()
                        , 60, "",getString(R.string.user_attribute_work_limit,60),
                        REQUEST_CODE_EDIT_JOB
                );
                return;
            case R.id.viewHobby:
                TrackUtil.trackScreenName("/user/about/edit/set/passionate");
                value=viewHobby.getmRightText().toString().equals(getString(R.string.value_no_set));
                EditInfoDetailActivity.startActivityWithoutShowDialig(
                        this, getString(R.string.user_attribute_hobby), value?"":viewHobby.getmRightText().toString()
                        , 60, getString(R.string.user_attribute_hobby_desc), getString(R.string.user_attribute_work_limit, 60),
                        REQUEST_CODE_EDIT_HOBBY
                );
                return;
            case R.id.viewLanguage:
                TrackUtil.trackScreenName("/user/about/edit/set/languages");
                intent = new Intent(this, ModifyUserLanguageActivity.class);
                intent.putExtra(KEY_VALUE,viewLanguage.getmRightText().toString());
                intent.putExtra(KEY_SELECTED_VALUES, viewLanguage.getmRightText().toString().split("/"));
                intent.putExtra(KEY_SELECT_ARRAY,getResources().getStringArray(R.array.languages));
                intent.putExtra(EditInfoDetailActivity.KEY_TITLE,getString(R.string.user_attribute_language));
                requestCode = REQUEST_CODE_EDIT_LANGUAGE;
                break;
            case R.id.viewIntroduction:
                TrackUtil.trackScreenName("/user/about/edit/set/description");
                intent = new Intent(this, EditInfoDetailActivity.class);
                intent.putExtra(KEY_DIALOG_TITLE,getString(R.string.user_attribute_introduce));
                intent.putExtra(KEY_PLACE_HOLDER,getString(R.string.user_attribute_introduce_desc));
                intent.putExtra(EditInfoDetailActivity.KEY_TITLE,getString(R.string.user_attribute_introduce));
                requestCode = REQUEST_CODE_EDIT_INTRODUCTION;
                break;
        }
        if (intent != null) {
            intent.putExtra(KEY_REQUEST_CODE, requestCode);
            startActivityForResult(intent, requestCode);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode,resultCode,data);
        boolean handleActivity = EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
            @Override
            public void onImagePickerError(Exception e, EasyImage.ImageSource source) {
                //Some error handling
            }

            @Override
            public void onImagePicked(File imageFile, EasyImage.ImageSource source) {
                //Handle the image
                boolean pickImageSuccess = mImageFetcherManager.cropImage(imageFile, tempPhotoFile, null);
                if (!pickImageSuccess) {
                    MessageUtils.showToast(R.string.feedback_data_err);
                }
            }

            @Override
            public void onCanceled(EasyImage.ImageSource source) {
                //Cancel handling, you might wanna remove taken photo if it was canceled
                if (source == EasyImage.ImageSource.CAMERA) {
                    File photoFile = EasyImage.lastlyTakenButCanceledPhoto(AppCoreRuntime.context);
                    if (photoFile != null) photoFile.delete();
                }
            }
        });
        if (!handleActivity){
            if (ImageFetcherManager.REQUEST_CODE_CROP_IMAGE == requestCode) {
                if (resultCode == Activity.RESULT_OK) {
                    Bitmap bp = GetImageHelper.getResizedBitmap(this, Uri.fromFile(tempPhotoFile));
                    if (bp == null) {
                    } else {
                        authorImg.setImageBitmap(bp);
                        updateImage();
                    }
                }
            } else {
                loadUserProfile();
            }
        }

    }

    protected void updateImage() {
        showLoading();
        CommonBusiness.getMobileOssToken(apiProxy);
    }
     public void completeAction() {
         Map<String, String> map = new HashMap<>();
         map.put("headPic", mUploadedAvaUrl);
         UserBusiness.updateProfile(apiProxy, map);
    }

}
